import React, { useEffect, useState } from 'react';
import { useAppStore } from '../stores/useAppStore';

const ItemsPage = () => {
  const { items, isLoading, error, fetchItems, createItem } = useAppStore();
  const [newItemTitle, setNewItemTitle] = useState('');

  useEffect(() => {
    fetchItems();
  }, [fetchItems]);

  const handleCreateItem = () => {
    if (newItemTitle.trim()) {
      createItem(newItemTitle);
      setNewItemTitle('');
    }
  };

  return (
    <div>
      <h2>创建新物品</h2>
      <input 
        type="text"
        value={newItemTitle}
        onChange={(e) => setNewItemTitle(e.target.value)}
        placeholder="输入物品标题"
      />
      <button onClick={handleCreateItem} disabled={isLoading}>
        {isLoading ? '创建中...' : '创建'}
      </button>

      <hr />

      <h2>物品列表 (来自后端)</h2>
      {isLoading && <p>加载中...</p>}
      {error && <p style={{ color: 'red' }}>错误: {error}</p>}
      {items.length > 0 ? (
        <ul>
          {items.map((item) => (
            <li key={item.id}>{item.title} (ID: {item.id})</li>
          ))}
        </ul>
      ) : (
        !isLoading && <p>没有物品。</p>
      )}
    </div>
  );
};

export default ItemsPage;
